package com.pet.shop.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.pet.config.Constants;
import com.pet.config.SessionConstants;
import com.pet.shop.entity.shop.AdvertInfo;
import com.pet.shop.entity.user.UserInfo;
import com.pet.shop.service.shop.IAdvertInfoService;
import com.pet.shop.service.user.IUserInfoService;
import com.pet.shop.utils.ApiResultUtil;
import com.pet.shop.vo.WxAuthVo;
import com.pet.shop.vo.WxUserVo;
import com.pet.utils.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/api/user")
public class UserInfoApiController {

    protected static final Logger logger = LoggerFactory.getLogger(UserInfoApiController.class);

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IAdvertInfoService advertInfoService;
    @Value("${wx.appId}")
    private String wxAppId;
    @Value("${wx.appSecret}")
    private String wxAppSecret;

    @RequestMapping("register")
    public Map<String, Object> register(@RequestBody UserInfo userInfo){
        userInfoService.insertEntity(userInfo);
        return ApiResultUtil.success(userInfo);
    }

    /**
     * 微信授权
     * @return
     */
    @RequestMapping("wxAuth")
    public Map<String, Object> wxAuth(HttpServletRequest request, @RequestBody WxAuthVo wxAuth){
        logger.info("微信授权请求：{}", JSONObject.toJSONString(wxAuth));
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+ wxAppId +"&secret="+ wxAppSecret+"&js_code="+ wxAuth.getCode() +"&grant_type=authorization_code";
        String resultStr = HttpUtil.requestOfGet(url);
        //{"session_key":"3cU6Fa2H35haVj0FXzLVRg==","openid":"oGlL945R9_hJC1L2FuOLFCepRRsk"}
        logger.info("微信授权返回值：{}", resultStr);
        JSONObject result = JSONObject.parseObject(resultStr);
        if(result.getString("errcode") != null){
            return ApiResultUtil.error_param("授权失败，请重试！");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setOpenid(result.getString("openid"));
        if(wxAuth.getUser() != null){
            userInfo.setAvatar(wxAuth.getUser().getAvatarUrl());
            userInfo.setNickname(wxAuth.getUser().getNickName());
        }
        userInfo.setCreateTime(new Date());
        userInfoService.insertEntity(userInfo);
        result.put("userId", userInfo.getId());
        result.put("sessionId", request.getSession().getId());
        SessionConstants.sessionUserMap.put(request.getSession().getId(), userInfo);
        return ApiResultUtil.success(result);
    }

    /**
     * 首页轮换广告
     * @return
     */
    @RequestMapping("advertList")
    public Map<String, Object> advertList(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        map.put("type",Constants.INDEX_TYPE);
        List<AdvertInfo> resultList = advertInfoService.queryAdvertInfo(map);
        if(resultList == null) resultList = new ArrayList<>();
        return ApiResultUtil.success(resultList);
    }

    /**
     * 我的菜单点进去
     * @return
     */
    @RequestMapping("userInfo")
    public Map<String, Object> userInfo(HttpServletRequest request){
        UserInfo userInfo = new UserInfo();
        return ApiResultUtil.success(userInfo);
    }



}
